package com.leetcode.sort;

/**
 * leetcode 148 排序链表
 */
public class Solution148 {
    public static class ListNode {
        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) {
            this.val = val;
        }
        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public ListNode sortList(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }

        // 使用快慢指针找到链表的中间
        ListNode point1 = head;
        ListNode point2 = head;
        while (point2 != null && point2.next != null && point2.next.next != null) {
            point1 = point1.next;
            point2 = point2.next.next;
        }
        ListNode leftHead = head;
        ListNode rightHead = point1.next;
        // 把链表断掉
        point1.next = null;

        // 排序左边
        leftHead = sortList(leftHead);
        rightHead = sortList(rightHead);

        // 合并
        return merge(leftHead, rightHead);
    }

    private ListNode merge(ListNode left, ListNode right) {
        if (left == null) {
            return right;
        }
        if (right == null) {
            return left;
        }

        ListNode head = new ListNode();
        ListNode point = head;
        while (left != null && right != null) {
            if (left.val <= right.val) {
                point.next = left;
                left = left.next;
            } else {
                point.next = right;
                right = right.next;
            }
            point = point.next;
        }

        // 处理剩下的
        if (left != null) {
            point.next = left;
        }

        if (right != null) {
            point.next = right;
        }

        return head.next;
    }

    public static void main(String[] args) {
        ListNode node1 = new ListNode(-1);
        ListNode node2 = new ListNode(5);
        node1.next = node2;
        ListNode node3 = new ListNode(3);
        node2.next = node3;
        ListNode node4 = new ListNode(4);
        node3.next = node4;
        ListNode node5 = new ListNode(0);
        node4.next = node5;

        Solution148 solution148 = new Solution148();
        System.out.println(solution148.sortList(node1));
    }
}
